package com.pubinfo.passbook.common.service.mss.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.common.config.ApplicationConfig;
import com.pubinfo.passbook.common.config.ProfileConfig;
import com.pubinfo.passbook.common.entity.*;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.mapper.*;
import com.pubinfo.passbook.common.model.bo.eip.ReceiveTaskParam;
import com.pubinfo.passbook.common.model.bo.uccp.ShortMessageParam;
import com.pubinfo.passbook.common.model.bo.witeoff.CityInfo;
import com.pubinfo.passbook.common.model.bo.witeoff.InvoiceInfo;
import com.pubinfo.passbook.common.model.bo.witeoff.MedicineOnJobOrRetireBO;
import com.pubinfo.passbook.common.model.bo.witeoff.WiteoffBase;
import com.pubinfo.passbook.common.model.bo.witeoff.subitem.MedicineOnJobOrRetireSubitem;
import com.pubinfo.passbook.common.model.constant.StaffStatusEnum;
import com.pubinfo.passbook.common.model.dto.witeoff.MedicineOnJobOrRetireDTO;
import com.pubinfo.passbook.common.model.dubbo.ESBServiceData;
import com.pubinfo.passbook.common.model.http.baseEntity.BaseBody;
import com.pubinfo.passbook.common.model.http.baseEntity.Baseinfo;
import com.pubinfo.passbook.common.model.http.baseEntity.Message;
import com.pubinfo.passbook.common.model.http.baseEntity.request.IRequest;
import com.pubinfo.passbook.common.model.http.baseEntity.request.MessageList;
import com.pubinfo.passbook.common.model.http.baseEntity.request.RequestEnvelope;
import com.pubinfo.passbook.common.model.http.request.AutoCreateWriteoff.AutoCreateWriteoffBody;
import com.pubinfo.passbook.common.model.http.request.AutoCreateWriteoff.AutoCreateWriteoffMessageList;
import com.pubinfo.passbook.common.model.http.request.GetSapNumber.GetSapNumberBody;
import com.pubinfo.passbook.common.model.http.request.GetSapNumber.GetSapNumberItems;
import com.pubinfo.passbook.common.model.http.response.GetAutoCreateWriteoff.WriteoffEnvelope;
import com.pubinfo.passbook.common.model.http.response.GetAutoCreateWriteoff.WriteoffMessage;
import com.pubinfo.passbook.common.model.ruler.PayInformation;
import com.pubinfo.passbook.common.model.ruler.Reimbursement;
import com.pubinfo.passbook.common.model.ruler.ReimbursementParam;
import com.pubinfo.passbook.common.model.ruler.UserAcc;
import com.pubinfo.passbook.common.model.vo.RuleAuditVo;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.witeoff.WiteoffResultCode;
import com.pubinfo.passbook.common.service.aviator.AviatorScriptService;
import com.pubinfo.passbook.common.service.dedicated.DedicatedService;
import com.pubinfo.passbook.common.service.dubbo.DubboService;
import com.pubinfo.passbook.common.service.master.*;
import com.pubinfo.passbook.common.service.mss.HttpService;
import com.pubinfo.passbook.common.service.ruler.CheckService;
import com.pubinfo.passbook.common.service.ruler.InformationService;
import com.pubinfo.passbook.common.service.ruler.RuleShengGongSiService;
import com.pubinfo.passbook.common.service.ruler.RuleWenZhouService;
import com.pubinfo.passbook.common.utils.UccpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Slf4j
@Service
@Primary
public class HttpServiceImpl implements HttpService {
    @Resource
    ApplicationConfig config;
    @Resource
    ProfileConfig profileConfig;
    @Value("${protest.budgetSet}")
    String budgetSet;
    @Autowired
    TRuleAuditMapper tRuleAuditMapper;
    @Autowired
    TRabbitmqPersonConvertMapper convertMapper;
    @Autowired
    DubboService vatService;
    @Autowired
    RuleWenZhouService wenZhouService;
    @Autowired
    TWiteoffInstanceSubitemService subitemService;
    @Autowired
    TSystemRoleService roleService;
    @Autowired
    RuleShengGongSiService shengGongSiService;
    @Autowired
    TWiteoffInstanceService instanceService;
    @Autowired
    TWiteoffAttchmentService attchmentService;
    @Autowired
    TWiteoffInvoiceInfoService invoiceInfoService;
    @Autowired
    TWiteoffOpenPickingService openPickingService;
    @Autowired
    TWiteoffPayMentService payMentService;
    @Autowired
    TWiteoffRelateSupplierService relateSupplierService;
    @Autowired
    InformationService informationService;
    @Autowired
    TRabbitmqPersonService personService;
    @Autowired
    TWiteoffShareAttachmentService shareAttachmentService;
    @Autowired
    AviatorScriptService scriptService;
    @Autowired
    CheckService ruleService;
    @Autowired
    DedicatedService excelService;
    @Autowired
    TRuleGenusService genusService;
    @Autowired
    TPassbookService passbookService;
    @Autowired
    TSourcePassbookMapper passbookMapper;
    @Autowired
    TRuleParamService paramService;
    @Autowired
    TSubsidiaryInfoMapper infoMapper;
    @Autowired
    DedicatedService dedicatedService;
    @Autowired
    TFileFtpMapper fileFtpMapper;
    @Autowired
    TSourceInvoiceMapper sourceInvoiceMapper;
    @Autowired
    TRuleUserWiteoffService witeoffService;
    @Autowired
    ITSourceArtificialService artificialService;
    @Autowired
    ITFileEnclosureFtpService itFileEnclosureFtpService;
    @Autowired
    TRuleAuditService tRuleAuditService;
    @Autowired
    TFileInfoMapper fileInfoMapper;
    @Autowired
    DubboService dubboService;
    @Autowired
    TWiteoffInstanceMapper tWiteoffInstanceMapper;
    @Autowired
    TSourceArtificialMapper artificialMapper;

    @Autowired
    TAutoWiteoffManageService manageService;
    protected Boolean isTest = false;
    @Value("${eip.cas.task-url}")
    private String taskUrl;
//
//    @Override
//    public List<TPassbook> selectInvoiceInfoPassbook(String startTime, String endTime) throws ParseException, UnirestException {
//        List<OutParam> outParams = synWriteoffInfoList(startTime, endTime);
//        List<TPassbook> tPassbookList = new ArrayList<>();
//        for (OutParam outParam : outParams) {
//            for (OutParamItem outParamItem : outParam.getItems()) {
//                for (OutParamInvoiceInfo outParamInvoiceInfo : outParamItem.getInvoiceInfos()) {
//                    List<TPassbook> tPassbooks = new ArrayList<>();
//                    TPassbook tPassbook = new TPassbook();
//                    tPassbook.setEinvoiceCode(outParamInvoiceInfo.getInvoiceNum());
//                    tPassbook.setEinvoiceNumber(outParamInvoiceInfo.getInvoiceCode());
//                    tPassbooks.add(tPassbook);
//                    List<TPassbook> passbooks = invoiceMapper.selectPassbookByFpdmAndFphm(tPassbooks);
//                    if (CollectionUtils.isEmpty(passbooks)) {
//                        log.error(outParamInvoiceInfo.toString());
//                    }
//                    tPassbookList.addAll(passbooks);
//                }
//            }
//        }
//
//
//        return tPassbookList;
//    }

//    @Override
//    public OutParam synWriteoffInfo(InputParamBody inputParamBody) throws UnirestException {
//        return null;
//    }

    /**
     * 在职员工报销
     *
     * @param jobDTO
     * @return
     * @throws IOException
     * @throws UnirestException
     */
    @SneakyThrows
    @Override
    public JsonResult<String> medicineOnJobAutoCreateWriteoff(MedicineOnJobOrRetireDTO jobDTO, Boolean isCheckPermission, String acctId) {
        //设置报账所需附件
        if (!CollectionUtils.isEmpty(jobDTO.getTFileEnclosureFtpIds())) {
            List<TFileEnclosureFtp> tFileEnclosureFtps = itFileEnclosureFtpService.getTFileEnclosureFtpByIds(jobDTO.getTFileEnclosureFtpIds());
            List<TWiteoffAttchment> tWiteoffAttchments = new ArrayList<>();
            for (TFileEnclosureFtp tFileEnclosureFtp : tFileEnclosureFtps) {
                TWiteoffAttchment tWiteoffAttchment = new TWiteoffAttchment(tFileEnclosureFtp);
                tWiteoffAttchments.add(tWiteoffAttchment);
            }
            jobDTO.setAttchmentAdds(tWiteoffAttchments);
        }

        if (ruleService.haveNonReimbursableItem(jobDTO.getInvoiceIds())) {
            return JsonResult.error(WiteoffResultCode.NOT_REIMBURSABLE_ITEM);
        }

        //在职医疗费报销规则主体逻辑
        //检查供属报销是否有权限

        List<TPassbook> shortMessageList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(jobDTO.getArtificials())) {
            //如果传入了票据，也不处理，因为医药费审核员已经加入了计算
            //如果添加了手工录入的单据,则加入单据的报销计算
            List<TSourceArtificial> artificialList = jobDTO.getArtificials();
            List<TSourceArtificial> hospitalizationList = artificialList.stream().filter(e -> 330602 == e.getType()).collect(Collectors.toList());
            List<TSourceArtificial> outpatientList = artificialList.stream().filter(e -> 330601 == e.getType()).collect(Collectors.toList());

            manualData(hospitalizationList, true,jobDTO.getDesc());
            manualData(outpatientList, true,jobDTO.getDesc());
        } else {

            //智慧医保数据有些没有，暂时统一进待办
            jobDTO.setIsNeedAudit(true);
            if (isCheckPermission) {
                if (!ruleService.checkUserPermission(jobDTO.getInvoiceIds(), acctId)) {
                    return JsonResult.error(WiteoffResultCode.FORBIDDEN);
                }
            }
            List<MedicineOnJobOrRetireSubitem> lineItems = jobDTO.getLineItems();
            //目前不支持报销多个子单,如果有多个,则返回错误
            if (lineItems.size() > 1) {
                return JsonResult.error(WiteoffResultCode.NOT_MANY_SUBITEM);
            }
            if (!ruleService.checkPassbookType(jobDTO.getInvoiceIds())) {
                return JsonResult.error(WiteoffResultCode.NOT_ONENESS);
            }
            TPassbook passbook = passbookService.getPassbookById(jobDTO.getInvoiceIds()).get(0);
            //报账时默认只报一个公司的票据
            CityInfo info = infoMapper.findCityInfoByNsrsbh(passbook.getNsrsbh());
            if (info == null || StringUtils.isEmpty(info.getCityName()) || StringUtils.isEmpty(info.getDistrictName())) {
                //如果没有找到地市或者是区县,则不进行报账.说明目前不支持该公司报账
                return JsonResult.error(WiteoffResultCode.NOT_SUPPORTED_CITY);
            }
            /**假定已经过滤了当前集合,都是同一员工的票据.
             * 在职与退休员工门诊费 短流程 不涉及扫描
             * 在职与退休员工住院费、特殊病种 长流程 涉及扫描
             * 手工录入单据 涉及扫描  长流程
             * 供属门诊费（不涉及扫描 单独走 长流程
             * 供属住院费（涉及扫描  单独走 长流程
             */
            Map<String, List<TPassbook>> groupMap = ruleService.group(jobDTO.getInvoiceIds());
            MedicineOnJobOrRetireDTO personnelJobDTO = new MedicineOnJobOrRetireDTO(jobDTO);
            List<TPassbook> personnelOpc = groupMap.get("personnelOpc");
            shortMessageList.addAll(submenu(jobDTO, personnelOpc, 3, true));
            //员工住院费
            List<TPassbook> personnelHospitalized = groupMap.get("personnelHospitalized");
            shortMessageList.addAll(submenu(personnelJobDTO, personnelHospitalized, 4, true));

        }

//        if (!CollectionUtils.isEmpty(shortMessageList)) {
//            String idNo = shortMessageList.get(0).getPayerPartyCode(); //报账人的身份证号
//            String acct = dubboService.getPersonsDetailByAcct(idNo);
//            ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
//            ShortMessageParam param = new ShortMessageParam("您好！您于" + UccpUtil.getSubmitDate(shortMessageList) + "提交单位报销的医药费票据共" + shortMessageList.size() + "张，根据补助政策核定报销金额为0元。", certDetail.getStaffPhone());
//            log.info(JSONObject.toJSONString(param));
//            vatService.sendShortMessage(param);
//        }
//
        //     return JsonResult.error(WiteoffResultCode.INVOICE_IS_NOT);
        return JsonResult.success("发起报账成功", jobDTO.getDetalis());
    }

    @Override
    public String userNsrsbhByAcct(String acct) {
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
        if (certDetail != null) {
            String areaName = certDetail.getSubsidiaryName();
            CityInfo info = infoMapper.findCityInfoByNsrsbh(areaName);
            if (info != null) {
                return info.getNsrsbh();
            }
        }
        return null;
    }

    @Override
    public void createWriteoffAgain(TWiteoffInstance tWiteoffInstance) {
        JSONObject json = tWiteoffInstance.getJson();
        MedicineOnJobOrRetireBO jobDTO = JSONObject.toJavaObject(json, MedicineOnJobOrRetireBO.class);
        jobDTO.setAgainWiteoffId(tWiteoffInstance.getId());
        jobDTO.setAgainOtherSystemMainId(tWiteoffInstance.getOtherSystemMainId());
        String pattern = "(ReimbursementList|ReimbursementDocument).*";
        jobDTO.setAttchmentAdds(jobDTO.getAttchmentAdds().stream().filter(e -> StringUtils.isEmpty(e.getAttchmentName()) || !Pattern.matches(pattern, e.getAttchmentName())).collect(Collectors.toList()));
        jobDTO.setOtherSystemMainId(UUID.randomUUID().toString());
        jobDTO.setIsNeedAudit(true);
        jobDTO.setIsAgain(true);
        postXmlAndSave(jobDTO, JSONObject.parseObject(JSON.toJSONString(jobDTO)), true);
    }

    @SneakyThrows
    @Override
    public void updateWiteoffInstance(MedicineOnJobOrRetireDTO jobDTO, String id) {
        jobDTO.setArtificials(artificialMapper.selectArtificialByOtherSystemMainId(jobDTO.getOtherSystemMainId()));
        Boolean isGenus = genusService.isGenus(jobDTO.getIdNo());
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(jobDTO.getIdNo());
        UserAcc userAcc = ruleService.getUserAcc(certDetail.staffCode, true);
        MedicineOnJobOrRetireBO bo = new MedicineOnJobOrRetireBO(jobDTO);
        Integer status = StaffStatusEnum.getEnumByStatus(certDetail.getStaffStatus()).getCode();
        MedicineOnJobOrRetireSubitem lineItem = new MedicineOnJobOrRetireSubitem(profileConfig.getActiveProfile(), bo.getSum(), status, isGenus, bo.getSapCompayCode(), userAcc);
        List<MedicineOnJobOrRetireSubitem> lineItems = new ArrayList<>();
        lineItems.add(lineItem);
        bo.setLineItems(lineItems);

        setJobOrRetireDTOId(bo);

        BaseBody baseBody = new BaseBody();
        Message message = new Message(new AutoCreateWriteoffMessageList(bo));
        baseBody.setBaseinfo(Baseinfo.createBaseinfo("AutoCreateWriteoff", new Date()));
        baseBody.setMessage(message);
        RequestEnvelope requestEnvelope = new RequestEnvelope();
        AutoCreateWriteoffBody body = new AutoCreateWriteoffBody();
        IRequest IRequest = new IRequest();
        IRequest.setBaseBody(baseBody);
        body.setIRequest(IRequest);
        requestEnvelope.setRequestBody(body);
        TWiteoffInstance instance = new TWiteoffInstance(bo, new XmlMapper().writeValueAsString(requestEnvelope), message.getMessage(), JSONObject.parseObject(JSON.toJSONString(jobDTO)));
        instance.setId(id);
        instanceService.updateById(instance);
    }

    @SneakyThrows
    @Override
    public void autoMedicineOnJobAutoCreateWriteoff(MedicineOnJobOrRetireDTO jobDTO, Boolean isCheckPermission) {
        //在职医疗费报销规则主体逻辑
        if (CollectionUtils.isEmpty(jobDTO.getInvoiceIds()) && CollectionUtils.isEmpty(jobDTO.getInvoiceInfos())) {
            return;
        }
        //智慧医保数据有些没有，暂时统一进待办
        jobDTO.setIsNeedAudit(true);
        //自动报账时，通知报账人报账金额
        TPassbook passbook = passbookService.getPassbookById(jobDTO.getInvoiceIds()).get(0);
        CityInfo info = infoMapper.findCityInfoByNsrsbh(passbook.getNsrsbh());
        if (info == null || StringUtils.isEmpty(info.getCityName()) || StringUtils.isEmpty(info.getDistrictName())) {
            String idNo = passbook.getPayerPartyCode(); //报账人的身份证号
            String acct = dubboService.getPersonsDetailByAcct(idNo);
            ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
            //如果没有找到地市或者是区县,则不进行报账.说明目前不支持该公司报账
            ShortMessageParam param = new ShortMessageParam("目前不支持" + info.getSubName() + "报账", certDetail.getStaffPhone());
            vatService.sendShortMessage(param);
            return;
        }
        /**假定已经过滤了当前集合,都是同一员工的票据.
         * 在职与退休员工门诊费 短流程 不涉及扫描
         * 在职与退休员工住院费、特殊病种 长流程 涉及扫描
         * 手工录入单据 涉及扫描  长流程
         * 供属门诊费（不涉及扫描 单独走 长流程
         * 供属住院费（涉及扫描  单独走 长流程
         */
        Map<String, List<TPassbook>> groupMap = ruleService.group(jobDTO.getInvoiceIds());
        List<TPassbook> personnelOpc = groupMap.get("personnelOpc");
        MedicineOnJobOrRetireDTO personnelJobDTO = new MedicineOnJobOrRetireDTO(jobDTO);
        submenu(jobDTO, personnelOpc, 3, false);
        //员工住院费
        List<TPassbook> personnelHospitalized = groupMap.get("personnelHospitalized");
        submenu(personnelJobDTO, personnelHospitalized, 4, false);
//        String idNo = passbook.getPayerPartyCode(); //报账人的身份证号
//        String acct = dubboService.getPersonsDetailByAcct(idNo);
//        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
//        if (!CollectionUtils.isEmpty(shortMessageList)) {
//            ShortMessageParam param = new ShortMessageParam("您好！您于" + UccpUtil.getSubmitDate(shortMessageList) + "提交单位报销的医药费票据共" + shortMessageList.size() + "张，根据补助政策核定报销金额为0元。", certDetail.getStaffPhone());
//            log.info(JSONObject.toJSONString(shortMessageList));
//           // vatService.sendShortMessage(param);
//        }
//
    }

    /**
     * 手工录入票据数据
     *
     * @param artificials
     * @return
     */
    @Override
    public JsonResult<String> manualData(List<TSourceArtificial> artificials, Boolean isShow,String desc) {
        if (CollectionUtils.isEmpty(artificials)) {
            log.error("没有找到该人力系统账号:" + artificials);
            return null;
        }
        TSourceArtificial artificial = artificials.get(0);
        String acct = artificial.getAcct();
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
        if (certDetail == null) {
            log.error("没有找到该人力系统账号:" + acct);
            return null;
        }
        InvoiceInfo invoiceInfo = null;
        Integer status = StaffStatusEnum.getEnumByStatus(certDetail.getStaffStatus()).getCode();
        String staffCode = certDetail.getStaffCode(); //人员编码
        UserAcc userAcc = ruleService.getUserAcc(staffCode, isShow);
        String areaName = certDetail.getSubsidiaryName();
        CityInfo info = infoMapper.findCityInfoByNsrsbh(areaName);
        String idNo = personService.findIdNoByAcct(artificial.getAcct());
        //如果没有到报账时间,则不发起报账;
        if (!ruleService.isReimbursementDate(info.getNsrsbh(), String.valueOf(artificial.getType()), idNo)) {
            log.error("根据" + info.getCityName() + info.getDistrictName() + "地区的相应规定当前没有到报账时间");
            return null;
        }
        BigDecimal sum = ruleService.checkArtificialSum(info, artificials);//计算可报销金额
        List<TWiteoffInvoiceInfo> invoiceInfos = TWiteoffInvoiceInfo.toList(sum);
        String sapCompayCode = sourceInvoiceMapper.selectCompanyType(areaName);

        MedicineOnJobOrRetireDTO dto = new MedicineOnJobOrRetireDTO(profileConfig.getActiveProfile(), status, sapCompayCode, invoiceInfo, userAcc, false, null, budgetSet, sum,desc);

        dto.setPayMentItems(new ArrayList<>());
        dto.setArtificials(artificials);
        dto.setNsrsbh(artificial.getNsrsbh());
        dto.setPhone(certDetail.getStaffPhone());
        setPayMentItems(dto, staffCode);
        if (330602 == artificial.getType()) {
            dto.setHospitalizationSum(sum);
            //加入住院手工报账票据
            artificials.stream().forEach(tSourceArtificial -> {
                dto.setHospitalizationNub(dto.getHospitalizationNub()+tSourceArtificial.getNumber());
                dto.setHospitalizationTotalAmount(dto.getHospitalizationTotalAmount().add(new BigDecimal(tSourceArtificial.getPayAmount())));
            });
        } else {
            dto.setOutpatientDepartmentSum(sum);
            //加入门诊手工报账票据
            artificials.stream().forEach(tSourceArtificial -> {
                dto.setOutpatientDepartmentNub(dto.getOutpatientDepartmentNub()+tSourceArtificial.getNumber());
                dto.setOutpatientDepartmentTotalAmount(dto.getOutpatientDepartmentTotalAmount().add(new BigDecimal(tSourceArtificial.getPayAmount())));
            });

        }
        List<TRuleUserWiteoff> witeoffs = TRuleUserWiteoff.toList(dto, acct);
        if (!isTest) {

            witeoffService.saveBatch(witeoffs); //保存报账用户金额
        }
        dto.setIdNo(idNo);
        setAttchmentAddsObj(dto, idNo);
        MedicineOnJobOrRetireBO bo = new MedicineOnJobOrRetireBO(dto);
        bo = setJobOrRetireDTOId(bo);
        log.info(JSONObject.toJSONString(bo));
        bo.setIsNeedAudit(true);
        return postXmlAndSave(bo, JSONObject.parseObject(JSON.toJSONString(dto)), true);
    }

    // type 1  供属门诊费 2 供属住院费 3 员工门诊费 4 员工住院费  供属暂不支持报账
    private List<TPassbook> submenu(MedicineOnJobOrRetireDTO jobDTO, List<TPassbook> passbookList, Integer type, Boolean isShow) {
        //如果没有到报账时间,则不发起报账;
        List<TPassbook> passbooks = new ArrayList<>();
        TPassbook passbook = passbookService.getPassbookById(jobDTO.getInvoiceIds()).get(0);
        if (!ruleService.isReimbursementDate(passbook.getNsrsbh(), passbook.getClassCode(), passbook.getPayerPartyCode())) {
            log.error("根据相应规定当前没有到报账时间");
            return passbooks;
        }
        Boolean isVertical = ruleService.haveVerticalPlate(jobDTO.getInvoiceIds());
        if (isVertical) {
            //如果包含竖版的票据，则设置走人工待办。
            jobDTO.setIsNeedAudit(true);
        }
        //如果是省公司才分单
        if (!CollectionUtils.isEmpty(passbookList)) {
            if (ruleService.isShengGongSi(passbookList)) {
                //满20,重发一单
                Integer pageSize = 20;
                Integer pageTotal = passbookList.size();
                Integer pageNumber = (pageTotal + pageSize - 1) / pageSize;

                for (int i = 1; i <= pageNumber; i++) {
                    Integer start = (i - 1) * pageSize;
                    List<TPassbook> passbookItem = passbookList.stream().skip(start).limit(pageSize).collect(Collectors.toList());
                    MedicineOnJobOrRetireDTO jobDTOItem = new MedicineOnJobOrRetireDTO(jobDTO, passbookItem);
                    if (type == 3) {
                        //测试阶段，不走短流程
                        jobDTOItem.setIsProcessShort(true);
                        jobDTOItem.setIsNeedImage(0);
                    }
                    passbooks.addAll(sendTo(jobDTOItem, isShow));
                }
            } else {
                MedicineOnJobOrRetireDTO jobDTOItem = new MedicineOnJobOrRetireDTO(jobDTO, passbookList);
                if (type == 3) {
                    //测试阶段，不走短流程
                    jobDTOItem.setIsProcessShort(true);
                    jobDTOItem.setIsNeedImage(0);
                }
                passbooks.addAll(sendTo(jobDTOItem, isShow));
            }

        }
        return passbooks;

    }

    @Override
    public List<TPassbook> sendTo(MedicineOnJobOrRetireDTO jobDTO, Boolean isShow) {
        BigDecimal sum = ruleService.checkPassbookSum(jobDTO);
        List<TPassbook> passbookList = passbookService.getPassbookById(jobDTO.getInvoiceIds());
        TPassbook passbook = passbookList.get(0);
        String idNo = passbook.getPayerPartyCode(); //报账人的身份证号
        String acct = dubboService.getPersonsDetailByAcct(idNo);
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
        jobDTO.setNsrsbh(passbook.getNsrsbh());
        List<TRuleUserWiteoff> witeoffs = TRuleUserWiteoff.toList(jobDTO, acct);
        if (sum.compareTo(BigDecimal.ZERO) == 1) { //为0,则不进行报销.
            jobDTO.setSum(sum);
            //jobDTO.setpi
            if (!isTest) { //测试时不保存
                witeoffService.saveBatch(witeoffs); //保存报账用户金额
            }
        }
//        else {
//            ShortMessageParam param = new ShortMessageParam("您好！您于" + UccpUtil.getSubmitDate(passbookList) + "提交单位报销的医药费票据共" + passbookList.size() + "张，根据补助政策核定报销金额为" + sum + "元。", certDetail.getStaffPhone());
//                vatService.sendShortMessage(param);
//            return JsonResult.error(WiteoffResultCode.NOT_REIMBURSEMENT_STANDARD);
//            return passbookList;
//          }

        String areaName = certDetail.getSubsidiaryName();
        String sapCompayCode = sourceInvoiceMapper.selectCompanyType(areaName);
        jobDTO.setPhone(certDetail.getStaffPhone());
        jobDTO.setIdNo(idNo);
        jobDTO.setSapCompayCode(sapCompayCode);
        jobDTO.setWiteoffs(witeoffs);
        setAttchmentAddsObj(jobDTO, idNo);
        Boolean isGenus = genusService.isGenus(idNo);
        String staffCode = ruleService.getStaffCode(idNo, isGenus);
        UserAcc userAcc = ruleService.getUserAcc(staffCode, isShow);
        jobDTO.setUserAcc(userAcc);
        setPayMentItems(jobDTO, staffCode);
        MedicineOnJobOrRetireBO bo = new MedicineOnJobOrRetireBO(jobDTO);
        bo = setJobOrRetireDTOId(bo);
        log.info(JSONObject.toJSONString(bo));
        Integer status = StaffStatusEnum.getEnumByStatus(certDetail.getStaffStatus()).getCode();
        MedicineOnJobOrRetireSubitem lineItem = new MedicineOnJobOrRetireSubitem(profileConfig.getActiveProfile(), sum, status, isGenus, sapCompayCode, userAcc);
        lineItem.setOtherSystemDetailId(UUID.randomUUID().toString());
        List<MedicineOnJobOrRetireSubitem> lineItems = new ArrayList<>();
        lineItems.add(lineItem);
        bo.setLineItems(lineItems);
        //暂时注释
        postXmlAndSave(bo, JSONObject.parseObject(JSON.toJSONString(jobDTO)), true);
        return new ArrayList<>();
    }

    public void setPayMentItems(MedicineOnJobOrRetireDTO jobDTO, String staffCode) {
        TWiteoffPayMent bank = new TWiteoffPayMent(staffCode, jobDTO.getSum());
        jobDTO.getPayMentItems().add(bank);
    }

    public void setPassbookSumAndLocked(WiteoffBase jobDTO) {

        List<TPassbook> tPassbooks = passbookService.getPassbookById(jobDTO.getInvoiceIds());
        if (!CollectionUtils.isEmpty(tPassbooks)) {

            tPassbooks.stream().forEach(tPassbook -> {
                tPassbook.setSystemIsLocked("Y");
            });
            passbookService.updateBatchById(tPassbooks);
        }
    }

    /**
     * @param jobDTO
     * @param idNo
     * @param type   0为票据  1 为手工录入单据
     */
    public void setAttchmentAddsObj(MedicineOnJobOrRetireDTO jobDTO, String idNo) {
        // String idNo = passbook.getPayerPartyCode(); //报账人的身份证号
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(idNo);
        //附件集合
        List<TFileEnclosureFtp> tFileEnclosureFtps = new ArrayList<>();
        if (!jobDTO.getIsNeedAudit()) {
            TFileEnclosureFtp fileFtp = excelService.createExcelByClass(createReimbursement(jobDTO, certDetail, idNo));
            tFileEnclosureFtps.add(fileFtp);
            //是省公司还需要生产报账详情列表
            if (jobDTO.getNsrsbh().equals("91330000744141180B") || jobDTO.getNsrsbh().equals("91330000MA27U07PX0")) {
                TFileEnclosureFtp fileEnclosureFtp = excelService.createShenGongSiExcel(new ReimbursementParam(passbookService.getPassbookById(jobDTO.getInvoiceIds()), jobDTO.artificials));
                tFileEnclosureFtps.add(fileEnclosureFtp);
            }
        }

        //电子票据集合
        List<TFileElectronicFtp> tFileElectronicFtps = new ArrayList<>();
        if (!CollectionUtils.isEmpty(jobDTO.getInvoiceIds())) {
            tFileElectronicFtps = fileFtpMapper.findAttchmentAddById(jobDTO.getInvoiceIds());
        }
        if (!CollectionUtils.isEmpty(jobDTO.getArtificials())) {
            List<TFileElectronicFtp> artificialList = artificialService.findFileFtpByArtificialList(jobDTO.getArtificials());
            tFileElectronicFtps.addAll(artificialList);
        }


        jobDTO.getAttchmentAdds().addAll(TWiteoffAttchment.toList(tFileEnclosureFtps, tFileElectronicFtps));
    }

    @SneakyThrows
    @Override
    public String GetSapNumber(List<GetSapNumberItems> account) {
        String postUrl = config.getEsb().getUrl() + config.getEsb().getApi().getGetSapNumber();
        BaseBody baseBody = new BaseBody();
        Message message = new Message(new MessageList(account));
        baseBody.setBaseinfo(Baseinfo.createBaseinfo("GetSapNumber", new Date()));
        baseBody.setMessage(message);
        RequestEnvelope requestEnvelope = new RequestEnvelope();
        GetSapNumberBody body = new GetSapNumberBody();
        IRequest IRequest = new IRequest();
        IRequest.setBaseBody(baseBody);
        body.setIRequest(IRequest);
        requestEnvelope.setRequestBody(body);
        //发送post请求
        String s = dedicatedService.getSapNumber(new XmlMapper().writeValueAsString(requestEnvelope));

        //处理&#60;和&#62;的乱码
        s = s.replaceAll("&#60;", "<").replaceAll("&#62;", ">");

        System.out.println(s);
        return s;
    }

    @SneakyThrows
    @Override
    public Boolean postByOtherSystemMainId(String otherSystemMainId) {
        List<TPassbook> passbooks = passbookMapper.selectPassbookByOtherSystemMainId(otherSystemMainId);

        TWiteoffInstance tWiteoffInstance = instanceService.getTwiteoffInstanceByOtherSystemMainId(otherSystemMainId);
        JSONObject json = tWiteoffInstance.getJson();
        MedicineOnJobOrRetireDTO jobDTO = JSONObject.toJavaObject(json, MedicineOnJobOrRetireDTO.class);
        jobDTO.setOtherSystemMainId(otherSystemMainId);

        Boolean isGenus = genusService.isGenus(jobDTO.getIdNo());
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(jobDTO.getIdNo());
        UserAcc userAcc = ruleService.getUserAcc(certDetail.staffCode, true);
        MedicineOnJobOrRetireBO bo = new MedicineOnJobOrRetireBO(jobDTO);
        Integer status = StaffStatusEnum.getEnumByStatus(certDetail.getStaffStatus()).getCode();
        MedicineOnJobOrRetireSubitem lineItem = new MedicineOnJobOrRetireSubitem(profileConfig.getActiveProfile(), bo.getSum(), status, isGenus, bo.getSapCompayCode(), userAcc);
        List<MedicineOnJobOrRetireSubitem> lineItems = new ArrayList<>();
        lineItems.add(lineItem);
        bo.setLineItems(lineItems);

        setJobOrRetireDTOId(bo);
        String pattern = "(ReimbursementList|ReimbursementDocument).*";
        bo.setAttchmentAdds(jobDTO.getAttchmentAdds().stream().filter(e -> StringUtils.isEmpty(e.getAttchmentName()) || !Pattern.matches(pattern, e.getAttchmentName())).collect(Collectors.toList()));
        TFileEnclosureFtp fileFtp = excelService.createExcelByClass(createReimbursement(jobDTO, certDetail, jobDTO.getIdNo()));
        bo.getAttchmentAdds().add(new TWiteoffAttchment(fileFtp));
        if (jobDTO.getNsrsbh().equals("91330000744141180B") || jobDTO.getNsrsbh().equals("91330000MA27U07PX0")) {
            TFileEnclosureFtp fileEnclosureFtp = excelService.createShenGongSiExcel(new ReimbursementParam(passbooks, jobDTO.artificials));
            bo.getAttchmentAdds().add(new TWiteoffAttchment(fileEnclosureFtp));
        }

        bo.setIsNeedAudit(false);

        postXmlAndSave(bo, JSONObject.parseObject(JSON.toJSONString(jobDTO)), false);


        BaseBody baseBody = new BaseBody();
        Message message = new Message(new AutoCreateWriteoffMessageList(bo));
        baseBody.setBaseinfo(Baseinfo.createBaseinfo("AutoCreateWriteoff", new Date()));
        baseBody.setMessage(message);
        RequestEnvelope requestEnvelope = new RequestEnvelope();
        AutoCreateWriteoffBody body = new AutoCreateWriteoffBody();
        IRequest IRequest = new IRequest();
        IRequest.setBaseBody(baseBody);
        body.setIRequest(IRequest);
        requestEnvelope.setRequestBody(body);

        tWiteoffInstance.setStatus((byte) -4);
        tWiteoffInstance.setXml(new XmlMapper().writeValueAsString(requestEnvelope));
        tWiteoffInstance.setJson(JSONObject.parseObject(JSON.toJSONString(jobDTO)));
        tWiteoffInstance.setMainXml(message.getMessage());
        instanceService.updateById(tWiteoffInstance);
        return true;
    }


    @Override
    public String passbookAmountSum(String acct, String type) {
        if (passbookMapper.passbookAmountSum(acct, type) == null) return "0";
        return passbookMapper.passbookAmountSum(acct, type);
    }

    @SneakyThrows
    public JsonResult<String> postXmlAndSave(WiteoffBase witeoffBase, JSONObject jsonObject, Boolean needSaveInstance) {
        String postUrl = config.getEsb().getUrl() + config.getEsb().getApi().getGainWriteoffInstStatus();
        BaseBody baseBody = new BaseBody();
        Message message = new Message(new AutoCreateWriteoffMessageList(witeoffBase));
        baseBody.setBaseinfo(Baseinfo.createBaseinfo("AutoCreateWriteoff", new Date()));
        baseBody.setMessage(message);
        RequestEnvelope requestEnvelope = new RequestEnvelope();
        AutoCreateWriteoffBody body = new AutoCreateWriteoffBody();
        IRequest IRequest = new IRequest();
        IRequest.setBaseBody(baseBody);
        body.setIRequest(IRequest);
        requestEnvelope.setRequestBody(body);
        TAutoWiteoffManage manage = witeoffBase.getManage();
        String account = witeoffBase.getAccount();
        if (witeoffBase.getSum().compareTo(BigDecimal.ZERO) == 1 && !isTest) {
            saveInstance(witeoffBase, new XmlMapper().writeValueAsString(requestEnvelope), message.getMessage(), jsonObject, needSaveInstance);

            if (!witeoffBase.getIsNeedAudit()) {
                //发送post请求
                String s = null;
                WriteoffEnvelope writeoffEnvelope = null;
                log.info(new XmlMapper().writeValueAsString(requestEnvelope));
                s = dedicatedService.createWriteoff(new XmlMapper().writeValueAsString(requestEnvelope));
                writeoffEnvelope = new XmlMapper().readValue(s, WriteoffEnvelope.class);
                s = s.replaceAll("&#60;", "<").replaceAll("&#62;", ">");
                log.info(writeoffEnvelope.getBody().getEResponse().getBaseBody().getMessage().getMessage());
                WriteoffMessage writeoffMessage = null;
                String thisMessage = writeoffEnvelope.getBody().getEResponse().getBaseBody().getMessage().getMessage().replaceAll("<!\\[CDATA\\[", "").replaceAll("\\]\\]>", "");
                writeoffMessage = new XmlMapper().readValue(thisMessage, WriteoffMessage.class);
                System.out.println(writeoffMessage);
            } else {
                //, infoMapper.selectAuditUserByNsrsbh(witeoffBase.getSapCompayCode())
                TRuleAudit tRuleAudit = new TRuleAudit(witeoffBase);
                if (account.indexOf("@") > 0) {
                    account = account.substring(0, account.indexOf("@"));
                }
                String auditAcct = roleService.findAcctByAcct(account);
                if (StringUtils.isEmpty(auditAcct)) {
                    //如果没有审核员，则报错
                    throw new ServiceException("请联系系统管理员，配置账号" + account + "相应公司的审核员");
                }
                //测试时，固定给晓迪处理
                tRuleAudit.setAcct(auditAcct);
//                tRuleAudit.setAcct("71094205");
                tRuleAuditService.save(tRuleAudit);
                // 在生成待办后，发送消息到eip，通知用户处理待办
                ReceiveTaskParam param = new ReceiveTaskParam(tRuleAudit, witeoffBase.getFillInName(), taskUrl);
                dubboService.receiveTaskInfo(param);
            }
            manage.setWiteoffId(witeoffBase.getOtherSystemMainId());
        }
        manage.setSum(witeoffBase.getSum());
        manage.setDetalis(witeoffBase.getDetalis());
        manage.setJson(jsonObject);
        manage.setIsTest(isTest);
        if (!StringUtils.isEmpty(account)) {
            if (account.indexOf("@") > 0) {
                account = account.substring(0, account.indexOf("@"));
            }
            manage.setAcct(account);
        }
        manage.setCount(witeoffBase.getInvoiceIds().size());
        manage.setId(null);
        manageService.save(manage); //报账金额为零才发送,后续生成报账单后发送不为零的短信
        String idNo = witeoffBase.getIdNo(); //报账人的身份证号
        String acct = dubboService.getPersonsDetailByAcct(idNo);
        List<TPassbook> tPassbooks = passbookService.getPassbookById(witeoffBase.getInvoiceIds());
        ESBServiceData.CertDetail certDetail = dubboService.getPersonsDetailByIdNo(acct);
        ShortMessageParam param = new ShortMessageParam("您好！您于" + UccpUtil.getSubmitDate(tPassbooks) + "提交单位报销的医药费票据共" + witeoffBase.getInvoiceIds().size() + "张，根据补助政策核定报销金额为" + witeoffBase.getSum() + "元。", certDetail.getStaffPhone());
        Boolean isSend = false;
        manage.setMsgContext(param.getOrderContent());
        if (CollectionUtils.isNotEmpty(witeoffBase.getInvoiceIds()) && witeoffBase.getSum().compareTo(BigDecimal.ZERO) == 0) {
            if (!isTest) {
                isSend = vatService.sendShortMessage(param);
                new LambdaUpdateChainWrapper<TPassbook>(passbookMapper).in(TPassbook::getEInvoiceId, witeoffBase.getInvoiceIds()).set(TPassbook::getLogId, manage.getId()).update();
            }

        }
        manage.setIsSend(isSend);
        manageService.saveOrUpdate(manage);
        if (!isTest) {
            setPassbookSumAndLocked(witeoffBase);//锁定票据
        }
        //更新id表票据表
        return JsonResult.success("成功");
    }

    @Transactional
    public void saveInstance(WiteoffBase witeoffBase, String xml, String mainXml, JSONObject json, Boolean needSaveInstance) {
        TWiteoffInstance instance = new TWiteoffInstance(witeoffBase, xml, mainXml, json);
        if (needSaveInstance) {
            instanceService.save(instance);
            if (!CollectionUtils.isEmpty(witeoffBase.getInvoiceIds())) {
                passbookMapper.insertPassbookWiteoff(instance.getId(), witeoffBase.getInvoiceIds());
                passbookMapper.updatePassbookWiteoffSum(instance.getId());
            }
            //保存报账子单
            subitemService.saveBatch(TWiteoffInstanceSubitem.toSubItemsList(witeoffBase.getLineItems(), witeoffBase.getOtherSystemMainId()));
            List<TSourceArtificial> artificials = witeoffBase.getArtificials();
            if (!CollectionUtils.isEmpty(artificials)) {
                List<String> artificialIds = artificials.stream().map(TSourceArtificial::getId).collect(Collectors.toList());
                artificialMapper.insertArtificialWiteoff(instance.getOtherSystemMainId(), artificialIds);
                artificialMapper.updateArtificialWiteoffSum(instance.getOtherSystemMainId());
                //锁定单据
                artificials.stream().forEach(art -> {
                    art.setSystemIsLocked("Y");
                });
                artificialService.saveOrUpdateBatch(artificials);
            }
            //如果是再次发起的报账，将这单所有票据的金额复制为上一次发起的票据金额
            if (witeoffBase.getIsAgain()) {
                passbookMapper.updateAgainPassbookWiteoffSum(instance.getId(), witeoffBase.getAgainWiteoffId());
                artificialMapper.updateAgainArtificialWiteoffSum(instance.getOtherSystemMainId(), witeoffBase.getAgainOtherSystemMainId());
            }
        }
        //保存关联表.

        if (!witeoffBase.getIsNeedAudit()) {
            TWiteoffInstance tWiteoffInstance = instanceService.getTwiteoffInstanceByOtherSystemMainId(witeoffBase.getOtherSystemMainId());
            List<TRuleUserWiteoff> witeoffs = witeoffBase.getWiteoffs();
            if (!CollectionUtils.isEmpty(witeoffs)) {
                witeoffs.stream().forEach(tRuleUserWiteoff -> {
                    tRuleUserWiteoff.setOtherSystemMainId(instance.getOtherSystemMainId());
                });
                witeoffService.saveOrUpdateBatch(witeoffs);
            }

            List<PayInformation> payInformations = witeoffBase.getPayInformations();
//            if (!CollectionUtils.isEmpty(payInformations)) {
//                //保存可报销金额到票据表
//
//                //   updateWrapper.eq("",);
//                for (PayInformation payInformation : payInformations) {
//                    passbookMapper.updateReimbursableSumById(payInformation,tWiteoffInstance.getId());
//                }
//
//            }

            //将attchments添加入数据库
            List<TWiteoffAttchment> attchments = witeoffBase.getAttchmentAdds();
            if (!StringUtils.isEmpty(attchments)) {
                attchments.stream().forEach(tWiteoffAttchment -> {
                    tWiteoffAttchment.setOtherSystemMainId(witeoffBase.getOtherSystemMainId());
                    tWiteoffAttchment.setId(null);
                });
            }
            attchmentService.saveBatch(attchments);
            //保存将附件表与报账单链接
            for (TWiteoffAttchment attchment : attchments) {
                if (attchment.getFileType() == 0) {
                    itFileEnclosureFtpService.updateTFileEnclosureFtp(instance.getOtherSystemMainId(), attchment.getAttchmentAdd());
                    attchment.setId(null);
                }
            }

            //将invoiceInfos添加入数据库
            List<TWiteoffInvoiceInfo> invoiceInfos = witeoffBase.getInvoiceInfos();
            if (!StringUtils.isEmpty(invoiceInfos)) {
                invoiceInfos.stream().forEach(tWiteoffInvoiceInfo -> {
                    tWiteoffInvoiceInfo.setWiteoffInstanceId(witeoffBase.getOtherSystemMainId());
                    tWiteoffInvoiceInfo.setId(null);
                });
            }
            invoiceInfoService.saveBatch(invoiceInfos);

            //将openPickings添加入数据库
            List<TWiteoffOpenPicking> openPickings = witeoffBase.getOpenItemPickings();
            if (!StringUtils.isEmpty(openPickings)) {
                openPickings.stream().forEach(openPicking -> {
                    openPicking.setOtherSystemMainId(witeoffBase.getOtherSystemMainId());
                    openPicking.setId(null);
                });
            }
            openPickingService.saveBatch(openPickings);

            //将payMents添加入数据库
            List<TWiteoffPayMent> payMents = witeoffBase.getPayMentItems();
            if (!StringUtils.isEmpty(payMents)) {
                payMents.stream().forEach(payMent -> {
                    payMent.setOtherSystemMainId(witeoffBase.getOtherSystemMainId());
                    payMent.setId(null);
                });
            }
            payMentService.saveBatch(payMents);
            //将relateSuppliers添加入数据库
            List<TWiteoffRelateSupplier> relateSuppliers = witeoffBase.getRelateSuppliers();
            if (!StringUtils.isEmpty(relateSuppliers)) {
                relateSuppliers.stream().forEach(relateSupplier -> {
                    relateSupplier.setOtherSystemMainId(witeoffBase.getOtherSystemMainId());
                    relateSupplier.setId(null);
                });
            }
            relateSupplierService.saveBatch(relateSuppliers);
            //将shareAttachments添加入数据库
            List<TWiteoffShareAttachment> shareAttachments = witeoffBase.getShareAttachmentItems();
            if (!StringUtils.isEmpty(shareAttachments)) {
                shareAttachments.stream().forEach(shareAttachment -> {
                    shareAttachment.setOtherSystemMainId(witeoffBase.getOtherSystemMainId());
                    shareAttachment.setId(null);
                });
            }
            shareAttachmentService.saveBatch(shareAttachments);
        }
    }

//
//    @SneakyThrows
//    @Override
//    public String sendPost(String xml, String url) {
//        //Unirest.setTimeouts(0, 0);
//        HttpResponse<String> response = Unirest.post(url)
//            .header("Authorization", config.getEsb().getAuthorization())
//            .header("User-Agent", "apifox/1.0.0")
//            .header("Content-Type", "application/xml").body(xml)
//            .asString();
//        return response.getBody();
//    }


    protected MedicineOnJobOrRetireBO setJobOrRetireDTOId(MedicineOnJobOrRetireBO base) {
        base.getLineItems().stream().forEach(item -> {
            if (StringUtils.isEmpty(item.getOtherSystemDetailId())) {
                item.setOtherSystemDetailId(UUID.randomUUID().toString());
            }
        });
        if (StringUtils.isEmpty(base.getOtherSystemMainId())) {
            base.setOtherSystemMainId(UUID.randomUUID().toString());
        }
        return base;
    }

    //生成excel所需要的对象
    @SneakyThrows
    private List<Reimbursement> createReimbursement(MedicineOnJobOrRetireDTO jobDTO, ESBServiceData.CertDetail
            certDetail, String idNo) {

        List<Reimbursement> reimbursements = new ArrayList<>();

        Boolean isGenus = genusService.isGenus(idNo);
        Reimbursement hospitalizationReimbursement = null;
        Reimbursement outpatientDepartmentReimbursement = null;
        String staffCode;
        if (isGenus) {
            TRuleGenus ruleGenus = genusService.findRuleGenusByidNo(idNo);
            staffCode = genusService.findAcctByidNo(idNo);
            hospitalizationReimbursement = new Reimbursement(jobDTO, certDetail, ruleGenus, jobDTO.getHospitalizationTotalAmount(), jobDTO.getHospitalizationSum(), (byte) 1, jobDTO.getHospitalizationNub());
            outpatientDepartmentReimbursement = new Reimbursement(jobDTO, certDetail, ruleGenus, jobDTO.getOutpatientDepartmentTotalAmount(), jobDTO.getOutpatientDepartmentSum(), (byte) 0, jobDTO.getOutpatientDepartmentNub());
        } else {
            hospitalizationReimbursement = new Reimbursement(jobDTO, certDetail, jobDTO.getHospitalizationTotalAmount(), jobDTO.getHospitalizationSum(), (byte) 1, jobDTO.getHospitalizationNub());
            outpatientDepartmentReimbursement = new Reimbursement(jobDTO, certDetail, jobDTO.getOutpatientDepartmentTotalAmount(), jobDTO.getOutpatientDepartmentSum(), (byte) 0, jobDTO.getOutpatientDepartmentNub());
            staffCode = dubboService.getPersonsDetailByAcct(idNo);
        }
        hospitalizationReimbursement.setSerialNumber("1");
        outpatientDepartmentReimbursement.setSerialNumber("2");
        reimbursements.add(hospitalizationReimbursement);
        reimbursements.add(outpatientDepartmentReimbursement);
//        UserAcc userAcc = ruleService.getUserAcc(staffCode);
//        jobDTO.setUserAcc(userAcc);

        List<RuleAuditVo> ruleAuditVos = tRuleAuditMapper.selectAcctAndAuditTime(jobDTO.getOtherSystemMainId());
        if (CollectionUtils.isNotEmpty(ruleAuditVos)) {
            reimbursements.add(new Reimbursement(ruleAuditVos.get(0).getAcct(), new SimpleDateFormat("yyyy-MM-dd").format(ruleAuditVos.get(0).getAuditTime())));
        } else {
            reimbursements.add(new Reimbursement("系统", new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        }
        return reimbursements;
    }
}
